layui.define(
  [
    "form",
    "table",
    "tree",
    "layer",
    "http_proxy",
    "right_bar",
    "carousel",
    "laydate",
    "mapDrawClick",
  ],
  function (exports) {
    var $ = layui.$,
      form = layui.form,
      table = layui.table,
      tree = layui.tree,
      carousel = layui.carousel,
      laydate = layui.laydate,
      mapDrawClick = layui.mapDrawClick,
      http_proxy = layui.http_proxy;

    var intervalFlag = true;

    var hls = new window.Hls();
    //日期时间选择器
    laydate.render({
      elem: "#test5",
    });
    $(".leftBarBtn").on("click", function () {
      let btn = $(".leftBarBtn i");
      if (btn.hasClass("layui-icon-left")) {
        btn.removeClass("layui-icon-left").addClass("layui-icon-right");
        $(".leftBar").css("display", "none");
        $(".guardPoint").css("left", "0px");
      } else {
        btn.removeClass("layui-icon-right").addClass("layui-icon-left");
        $(".leftBar").css("display", "block");
        $(".guardPoint").css("left", "300px");
      }
    });
    $(".rightBarBtn").on("click", function () {
      let btn = $(".rightBarBtn i");
      if (btn.hasClass("layui-icon-down")) {
        btn.removeClass("layui-icon-down").addClass("layui-icon-up");
        $(".rightBottomBar").css("display", "none");
      } else {
        btn.removeClass("layui-icon-up").addClass("layui-icon-down");
        $(".rightBottomBar").css("display", "block");
      }
    });

    //清空
    $(".clearForm").on("click", function () {
      $(".leftData").css("display", "block");
      $(".leftDataHistory").css("display", "none");
      $("#treeclass").text("请选择故障树");
      $("#grainProperty").val("");
      $(".finishBox .layui-table-body tr").attr({
        style: "background-color:transparent",
      }); //其他tr恢复颜色
      $(".falutPoint .layui-table-body tr").attr({
        style: "background-color:transparent",
      }); //其他tr恢复颜色
      // $('#selectForm')[0].reset()
      // form.render();

      mapDrawClick.fallbackToTrueTime();

      intervalFlag = true;
    });
    // 查询历史数据
    form.on("submit(LAY-search)", function (data) {
      $(".leftData").css("display", "none");
      $(".leftDataHistory").css("display", "block");
      $(".rightAbottom").css("display", "none");

      //清除定时器
      intervalFlag = false;
      //隐藏实时数据
      mapDrawClick.queryHistory();

      table.reload("history", {
        where: data.field,
      });
    });

    //正线值守点查询
    form.on("submit(dutyPointQueryButton)", function (data) {
      $.ajax({
        url: http_proxy("/fault/getRightLineGuardPointInfoList"),
        type: "post",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(data.field),
        success: function (rep) {
          if (rep.data.length > 0) {
            mapDrawClick.drawDutyPoint(rep);
          }
        },
      });
    });

    //正线值守点清除
    $("#dutyPointClear").on("click", function () {
      $("#dutyPointMajor").text("请选择专业");
      $("#dutyPointMajorValue").val("");
      mapDrawClick.clearDutyPointMarker();
    });

    table.render({
      elem: "#history",
      id: "history",
      async: true,
      smartReloadModel: true,
      url: http_proxy("/fault/getQueryhistoryFaultListInfo"), //模拟接口
      where: { type: 2 },
      method: "post",
      contentType: "application/json",
      skin: "nob",
      height: "full-320",
      parseData: function (res) {
        return {
          code: 0,
          count: res.count,
          data: res.data,
          msg: "",
        };
      },
      cols: [
        [{ title: "时间结果", minWidth: 100, templet: "#historyContent" }],
      ],
      text: {
        none: "暂无数据",
      },
      page: {
        groups: 5,
        first: false,
        last: false,
        layout: ["prev", "page", "next"],
      },
      done: function (res) {
        tdTitle();
        $("th").hide();
      },
    });
    $("th").hide(); //表头隐藏的样式

    //请选择故障数
    var title = [];
    class NodeTitleFilter {
      constructor() {
        this.title = [];
        this.flag = false;
      }
      Nodetitle(flag, el, fn) {
        this.title = [];
        this.title[0] = {};
        this.title[0]["title"] = el.title;
        this.title[0]["id"] = el.id;
        // this.title.push(el.title);
        this.NodeFlag(el);
        fn(this.title);
      }
      NodeFlag(el) {
        if (el && el.children != undefined) {
          for (let i = 0; i < el.children.length; i++) {
            // this.title.push(el.children[i].title);
            let resObj = null;
            resObj = {
              title: el.children[i].title,
              id: el.children[i].id,
            };
            this.title.push(resObj);
            // console.log(el.children[i].id)
            this.NodeFlag(el.children[i]);
          }
        }
      }
    }
    var nodeCheck = new NodeTitleFilter();
    $.ajax({
      url: http_proxy("/getEquipment/tree"),
      type: "get",
      datatype: "json",
      async: false,
      success: function (result) {
        nodes = result.data.data1;
      },
    });
    tree.render({
      elem: "#classtree", //绑定元素
      showCheckbox: true,
      data: nodes,
      id: "treeList",
      oncheck: function (node) {
        var checkedData = tree.getChecked("treeList"); //获取选中节点的数据
        let titleThat = [];
        checkedData.map((res) => {
          nodeCheck.Nodetitle(true, res, (e) => {
            titleThat.push(...e);
          });
        });
        //单独抽离id与title
        let idArr = [];
        let titleArr = [];
        titleThat.map((res) => {
          titleArr.push(res.title);
        });
        titleThat
          .filter((res) => {
            return res.id != "";
          })
          .map((res) => {
            idArr.push(res.id);
          });

        if (titleArr.length <= 0) {
          titleArr = ["请选择故障树"];
        }
        //所有选中的title
        // console.log(titleArr);
        //所有选中的id
        // console.log(idArr)
        let titleJoion = titleArr.join(",");
        var $select = $($(this)[0].elem).parents(".layui-form-select");
        $select
          .find(".layui-select-title span")
          .html(titleJoion)
          .end()
          .find("input:hidden[name='gzSb']")
          .val(idArr);
      },
    });
    $(".downpanel")
      .on("click", ".layui-select-title", function (e) {
        $(".layui-form-select")
          .not($(this).parents(".layui-form-select"))
          .removeClass("layui-form-selected");
        $(this).parents(".downpanel").toggleClass("layui-form-selected");
        layui.stope(e);
      })
      .on("click", "dl i", function (e) {
        layui.stope(e);
      })
      .on("click", ".layui-tree-txt", function (e) {
        layui.stope(e);
      })
      .on("click", ".layui-icon-ok", function (e) {
        layui.stope(e);
      });
    $(".dropDown").on("click", function (e) {
      $(".layui-form-select").removeClass("layui-form-selected");
    });
    //表格鼠标悬浮查看隐藏内容
    function tdTitle() {
      $("th").each(function (index, element) {
        $(element).attr("title", $(element).text());
      });
      $("td").each(function (index, element) {
        $(element).attr("title", $(element).text());
      });
    }
    //线路
    $.ajax({
      url: http_proxy("/line/getLineInfo"),
      async: true,
      dataType: "json",
      type: "get",
      success: function (data) {
        $.each(data.data.lineInfoList, function (index, item) {
          $("#lineRoad").append(new Option(item.lineName, item.lineId));
        });
        form.render("select");
      },
      error: function (errorMsg) {
        console.log("请求数据失败");
      },
    });
    //专业
    $.ajax({
      url: http_proxy("/fault/gzZyList"),
      async: true,
      dataType: "json",
      type: "get",
      success: function (data) {
        $.each(data.data.gzZyList, function (index, item) {
          $("#majorList").append(new Option(item.company, item.coId));
        });
        form.render("select");
      },
      error: function (errorMsg) {
        console.log("请求数据失败");
      },
    });
    //应急事件数
    function getFaultNum() {
      $.ajax({
        type: "get",
        async: true, //异步执行
        url: http_proxy("/fault/getFaultNum"),
        dataType: "json", //返回数据形式为json
        success: function (data) {
          var dataData = data.data.faultNum;
          $(".handleNum").html(dataData.ocurranceNum - dataData.completeNum);
          $(".hanpenNum").html(dataData.ocurranceNum);
        },
        error: function (errorMsg) {
          console.log("请求数据失败");
        },
      });
    }
    getFaultNum();

    //未处理完成
    table.render({
      elem: "#untreated",
      id: "untreated",
      async: true,
      url: http_proxy("/fault/getUnResolveFaultListInfo"), //模拟接口
      where: { type: 1 },
      method: "post",
      contentType: "application/json",
      skin: "nob",
      height: "400",
      parseData: function (res) {
        return {
          code: 0,
          count: res.count,
          data: res.data,
          msg: "",
        };
      },
      cols: [[{ field: "faultContent", title: "内容", width: "100%" }]],
      page: {
        groups: 5,
        first: false,
        last: false,
        layout: ["prev", "page", "next"],
      },
      limit: 10,
      text: {
        none: "暂无数据",
      },
      done: function (req) {
        mapDrawClick.drawTodayFault(req);
        tdTitle();
      },
    });
    table.on("row(untreated)", function (obj) {
      $(".finishBox .layui-table-body tr").attr({
        style: "background-color:transparent",
      }); //其他tr恢复颜色
      var data_index = $(this).attr("data-index"); //得到当前的tr的index
      $(".falutPoint .layui-table-body tr").attr({
        style: "background-color:transparent",
      }); //其他tr恢复颜色
      $(
        ".falutPoint .layui-table-body tr[data-index=" + data_index + "]"
      ).attr({ style: "background-color:rgba(192, 192, 192, 0.5)" }); //改变当前tr颜色
      $(".rightAbottom").css("display", "block");
      $("#bottomBar").css("display", "block");
      $(".flowCount").text(obj.data.faultContent);
      $(".flowCount").attr({
        title: obj.data.faultContent != null ? obj.data.faultContent : "--",
      });
      layui.right_bar.renderRightBar(obj.data.faultId + "");
      $(".shape").css("display", "none");
      //点击左侧的应急事件
      mapDrawClick.clickTrueTimeFault(obj.data);
      //轮播
      function initCarousel() {
        $.ajax({
          url: http_proxy("/fault/getFaultPictureListInfo"),
          type: "post",
          data: {
            faultId: obj.data.faultId,
          },
          dataType: "json",
          success: function (data) {
            var str, str1;
            var pictureInfoList2 = [];
            var pictureInfoList1 = [];
            if (data.data.pictureInfoList.length != 0) {
              pictureInfoList1 = data.data.pictureInfoList;
              pictureInfoList2 = JSON.parse(JSON.stringify(pictureInfoList1));
              var compare = function (obj1, obj2) {
                var val1 = obj1.infoId;
                var val2 = obj2.infoId;
                if (val1 > val2) {
                  return 1;
                } else if (val1 < val2) {
                  return -1;
                } else {
                  return 0;
                }
              };
              pictureInfoList2 = pictureInfoList2.sort(compare);
              // console.log(pictureInfoList1);
              // console.log(pictureInfoList2);
              // $.each(pictureInfoList1,function (i,n) {
              //     str += '<div>\n' +
              //         '         <img src="'+n.fileUrl+'" alt="">\n' +
              //         '      </div>';
              //     $('#preview1').html(str);
              // });

              $.each(pictureInfoList2, function (i, n) {
                str1 +=
                  "<div>\n" +
                  '         <img src="' +
                  n.fileUrl +
                  '" alt="">\n' +
                  "      </div>";
                $("#preview2").html(str1);
              });
            } else {
              str = "";
              str1 = "";
              pictureInfoList2 = [];
              pictureInfoList1 = [];
              // $('#preview1').html(str);
              $("#preview2").html(str1);
            }
            var inss = layer.photos({
              photos: "#carouselView1",
              anim: 5, //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
              shade: [0.9, "#032A56"],
              closeBtn: 1,
            });
            layer.photos({
              photos: "#carouselView2",
              anim: 5, //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
              shade: [0.9, "#032A56"],
              title: false,
              closeBtn: 1,
            });
            // // 改变下时间间隔、动画类型、高度
            carousel.render({
              elem: "#carouselView1",
              width: "100%", //设置容器宽度
              arrow: "always", //始终显示箭头
              height: "190px",
              indicator: "none",
            });
            //改变下时间间隔、动画类型、高度
            carousel.render({
              elem: "#carouselView2",
              width: "100%", //设置容器宽度
              arrow: "always", //始终显示箭头
              height: "190px",
              indicator: "none",
            });
          },
        });
      }
      initCarousel();

      var url = "http://10.2.128.82:8000/live/090.m3u8";
      if (Hls.isSupported()) {
        var video = document.getElementsByTagName("video")[0];
        if (hls.url == undefined || hls.url == "") {
          hls.attachMedia(video);
        }
        if (hls.url != url) {
          hls.loadSource(url);
        }
        hls.on(Hls.Events.MANIFEST_PARSED, function () {
          console.log("加载成功");
          video.play();
        });
      } else if (video.canPlayType("application/vnd.apple.mpegurl")) {
        video.src = url;
        video.addEventListener("canplay", function () {
          video.play();
        });
      }
    });

    //历史应急事件点击
    table.on("row(history)", function (obj) {
      var data_index = $(this).attr("data-index"); //得到当前的tr的index
      $(".historyTable .layui-table-body tr").attr({
        style: "background-color:transparent",
      }); //其他tr恢复颜色
      $(
        ".historyTable .layui-table-body tr[data-index=" + data_index + "]"
      ).attr({ style: "background-color:rgba(192, 192, 192, 0.5)" }); //改变当前tr颜色

      mapDrawClick.drawHistoryOrCompleteFault(obj, true);
    });
    //今日已完成应急事件点击
    table.on("row(alarmComprehensive)", function (obj) {
      $(".falutPoint .layui-table-body tr").attr({
        style: "background-color:transparent",
      }); //其他tr恢复颜色
      var data_index = $(this).attr("data-index"); //得到当前的tr的index
      $(".finishBox .layui-table-body tr").attr({
        style: "background-color:transparent",
      }); //其他tr恢复颜色
      $(".finishBox .layui-table-body tr[data-index=" + data_index + "]").attr({
        style: "background-color:rgba(192, 192, 192, 0.5)",
      }); //改变当前tr颜色
      $(".rightAbottom").css("display", "block");
      $("#bottomBar").css("display", "none");
      $(".flowCount").text(obj.data.faultContent);
      $(".flowCount").attr({
        title: obj.data.faultContent != null ? obj.data.faultContent : "--",
      });
      layui.right_bar.renderRightBar(obj.data.faultId + "");
      $(".KeyInformationSection").css("display", "none");

      mapDrawClick.drawHistoryOrCompleteFault(obj, false);
    });
    //处理完成
    table.render({
      elem: "#finishTreated",
      url: http_proxy("/fault/getResolveFaultListInfo"), //模拟接口
      where: { type: 1 },
      method: "post",
      contentType: "application/json",
      skin: "nob",
      height: "full-820",
      parseData: function (res) {
        return {
          code: 0,
          count: res.count,
          data: res.data,
          msg: "",
        };
      },
      cols: [[{ field: "faultContent", title: "处理结果" }]],
      limit: 5,
      page: {
        groups: 5,
        first: false,
        last: false,
        layout: ["prev", "page", "next"],
      },
      text: {
        none: "暂无数据",
      },
      done: function (res) {
        tdTitle();
      },
    });
    $("th").hide(); //表头隐藏的样式

    mapDrawClick.drawTeamsMarker();

    //页面加载完毕后，加载前端写死的装备点
    mapDrawClick.loadEmergency();
    mapDrawClick.maputilInit();

    //定时刷新未完成应急事件列表
    function reload() {
      console.log("刷新列表");
      if (intervalFlag) {
        table.reload("untreated", {});
        table.reload("finishTreated", {});
        getFaultNum();
      }
    }

    setInterval(reload, layui.setter.timerInterval);

    // 正线值守点线路
    $.ajax({
      url: http_proxy("/fault/getGuardPointLineInfo"),
      async: true,
      dataType: "json",
      type: "get",
      success: function (data) {
        $.each(data.data, function (index, item) {
          $("#pointLine").append(new Option(item, item));
        });
        form.render("select");
      },
      error: function (errorMsg) {
        console.log("请求数据失败");
      },
    });
    // 正线值守点专业
    $.ajax({
      url: http_proxy("/fault/getGuardPointProfession"),
      type: "get",
      datatype: "json",
      async: false,
      success: function (result) {
        pointProfessions = result.data;
      },
    });
    tree.render({
      elem: "#majorTree", //绑定元素
      showCheckbox: true,
      data: pointProfessions,
      id: "majorTree",
      oncheck: function (node) {
        var checkedData = tree.getChecked("majorTree"); //获取选中节点的数据
        console.log(checkedData);
        let titleThat = [];
        checkedData.map((res) => {
          nodeCheck.Nodetitle(true, res, (e) => {
            titleThat.push(...e);
          });
        });
        //单独抽离id与title
        let idArr = [];
        let titleArr = [];
        titleThat.map((res) => {
          titleArr.push(res.title);
        });
        titleThat
          .filter((res) => {
            return res.id != "";
          })
          .map((res) => {
            idArr.push(res.id);
          });

        if (titleArr.length <= 0) {
          titleArr = ["请选择专业"];
        }
        //所有选中的title
        console.log(titleArr);
        //所有选中的id
        console.log(idArr);
        let titleJoion = titleArr.join(",");
        var $select = $($(this)[0].elem).parents(".layui-form-select");
        $select
          .find(".layui-select-title span")
          .html(titleJoion)
          .end()
          .find("input:hidden[name='gzSb']")
          .val(idArr);
        $select
          .find(".layui-select-title span")
          .html(titleJoion)
          .end()
          .find("input:hidden[name='zy']")
          .val(idArr);
      },
    });
    $(".majorDropDown")
      .on("click", ".layui-select-title", function (e) {
        $(".layui-form-select")
          .not($(this).parents(".layui-form-select"))
          .removeClass("layui-form-selected");
        $(this).parents(".majorDropDown").toggleClass("layui-form-selected");
        layui.stope(e);
      })
      .on("click", "dl i", function (e) {
        layui.stope(e);
      })
      .on("click", ".layui-tree-txt", function (e) {
        layui.stope(e);
      })
      .on("click", ".layui-icon-ok", function (e) {
        layui.stope(e);
      });
    $(".majorDropDown ").on("click", function (e) {
      $(".layui-form-select").removeClass("layui-form-selected");
    });
    exports("home", {});
  }
);
